<?php

namespace app\admin\controller;

use app\BaseController;
use app\common\entity\ResponseData;
use app\common\exception\auth\UserDontExist;
use app\common\library\Captcha;
use app\model\User;
use edward\captcha\facade\CaptchaApi;
use Exception;
use think\helper\Str;

class Login extends BaseController
{
    public function login($phone, $code, $key)
    {
        if (Captcha::check($code, $key)) {
            $password = input('password', '');
            $user = User::where(['username' => $phone])->find();
            if (!$user) {
                throw new UserDontExist();
            }
            if($user->password != md5(md5($password).$user->salt)){
                // throw new Exception('密码错误');
            }
            $user['token'] = Str::random(8);
            cache('user_' . $user->id, $user, 24 * 60 * 60);
            return ResponseData::success($user);
        }
        return ResponseData::error('验证码错误', COMMON_ERROR);
    }

    public function smsLogin($phone, $code, $key = '')
    {
        if (CaptchaApi::checkSMS($code,$key)  || input('code') == COMMON_VALID_CODE){
            $user = User::where(['username'=>$phone])->find();
            if (!$user) {
                throw new UserDontExist();
            }
            $user['token'] = Str::random(8);
            cache('user_'.$user->id, $user, 24*60*60);
            return ResponseData::success($user);
        }
        return ResponseData::error('短信验证码错误');
    }

    public function getValidatCode()
    {
        $data = Captcha::create(input('key', ''));
        return ResponseData::success($data);
    }
}

